<?php

class ymcms{
 
	public static function article_read($yuming_id, $id){
		$folderId = floor($id/1000)*1000;
		$filepath = DATA."/content/$yuming_id/$folderId/$id.txt";
		$filepath2 = DATA."/content/$folderId/$id.txt";
		$body="";
		if(is_file($filepath)){
			$body = file_get_contents($filepath);
		} else if ($filepath2) {
			$body = file_get_contents($filepath);
		}
		return $body;
	}

	public static function article_write($yuming_id, $id, $filecontent){
		$folderId = floor($id/1000)*1000;
		$filepath = DATA."/content/$yuming_id/$folderId/$id.txt";
		$filedir = dirname($filepath);
		if(!is_dir($filedir)){
			mkdir($filedir, 0777, true);
		}
		if(file_put_contents($filepath,$filecontent)){
			return true;
		}
		return false;
	}

	public static function article_delete($id){
		$folderId = floor($id/1000)*1000;
		$filepath = DATA."/content/$folderId/$id.txt";
		if( is_file($filepath) && @unlink($filepath)){
			return true;
		}
		return false;
	}

	public static function get_themes(){
		$dir = ROOT."/templates";
		$handle = opendir($dir); 
		$themes = array(); 
		while ($file = readdir($handle)) 
		{ 
			if ($file != "." && $file != "..") { 
				$themes[$file] = self::get_theme_info($file);
			}
		}
        uksort($themes, function($a, $b){if(strpos($b, "default")===0){ return true; }});
		closedir($handle); 
		return $themes;
	}

	public static function get_theme_info($name){
		$configXml = ROOT.'/templates/'.$name.'/yumingcms.xml';
		if(is_file($configXml)){
			//$xml = simplexml_load_file($configXml);
			$xmlstring = file_get_contents($configXml);
			$xml = new SimpleXMLElement($xmlstring);
			//dump($xml);
		}else{
			$xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<root>\r\n<engine>default</engine>\r\n</root>";
			$xml = new SimpleXMLElement($xmlstring);
		}
		$xml = json_decode(json_encode($xml), true);
		$xml['name'] = !isset($xml['name'])?$name:$xml['name'];
		return $xml;
	}

}

